import React, { createContext, useContext, useState, useEffect, useCallback } from 'react';
import portfolioApi from '../utils/database';

// 创建上下文
const PortfolioContext = createContext();

// 提供上下文的组件
export const PortfolioProvider = ({ children }) => {
  // 状态管理
  const [works, setWorks] = useState([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [filteredWorks, setFilteredWorks] = useState([]);
  const [isAdmin, setIsAdmin] = useState(false);
  const [currentAdmin, setCurrentAdmin] = useState(null);
  const [adminPassword, setAdminPassword] = useState('');
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [currentWork, setCurrentWork] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  
  // 课程相关状态
  const [courses, setCourses] = useState([]);
  const [currentCourse, setCurrentCourse] = useState(null);
  const [isCourseModalOpen, setIsCourseModalOpen] = useState(false);
  
  // 分页状态
  const [pagination, setPagination] = useState({
    page: 1,
    limit: 12,
    total: 0,
    totalPages: 0
  });

  // 从数据库加载作品（支持分页和课程筛选）
  const loadWorks = useCallback(async (page = 1, limit = 12, courseId = null) => {
    try {
      setLoading(true);
      setError(null);
      
      console.log('🔄 开始加载作品数据...');
      console.log('📡 API URL:', portfolioApi.baseUrl);
      
      // 初始化 API 连接
      console.log('🔗 测试 API 连接...');
      await portfolioApi.init();
      console.log('✅ API 连接成功');
      
      // 获取作品数据（支持分页）
      console.log('📥 获取作品数据...');
      const result = await portfolioApi.getAllWorks(page, limit, courseId);
      console.log('✅ 成功获取作品数据:', result.works.length, '个作品');
      
      setWorks(result.works);
      setFilteredWorks(result.works);
      setPagination({
        page: result.page,
        limit: result.limit,
        total: result.total,
        totalPages: result.totalPages
      });
    } catch (err) {
      console.error('❌ 加载作品失败:', err);
      console.error('🔍 错误详情:', {
        message: err.message,
        stack: err.stack,
        apiUrl: portfolioApi.baseUrl
      });
      
      const errorMessage = err.message.includes('Failed to fetch') 
        ? `无法连接到服务器 (${portfolioApi.baseUrl})。请检查：\n1. 远程服务器是否运行\n2. 网络连接是否正常\n3. 防火墙设置是否正确`
        : err.message || '加载作品失败，请检查网络连接和后端服务';
        
      setError(errorMessage);
    } finally {
      setLoading(false);
    }
  }, []);

  // 加载课程数据
  const loadCourses = async (adminId = null) => {
    try {
      const coursesData = await portfolioApi.getAllCourses(adminId);
      setCourses(coursesData);
      return coursesData;
    } catch (err) {
      console.error('加载课程失败:', err);
      setError(err.message || '加载课程失败');
      throw err;
    }
  };

  // 加载管理员的作品（通过课程关联）
  const loadAdminWorks = async (adminId) => {
    try {
      setLoading(true);
      // 获取该管理员的所有作品
      const adminWorks = await portfolioApi.getAdminWorks(adminId);
      setWorks(adminWorks);
      setFilteredWorks(adminWorks);
      setPagination({
        page: 1,
        limit: adminWorks.length,
        total: adminWorks.length,
        totalPages: 1
      });
    } catch (err) {
      console.error('加载管理员作品失败:', err);
      setError(err.message || '加载管理员作品失败');
    } finally {
      setLoading(false);
    }
  };

  // 初始加载作品
  useEffect(() => {
    loadWorks();
  }, []);

  // 处理搜索
  useEffect(() => {
    const performSearch = async () => {
      if (!searchTerm) {
        setFilteredWorks(works);
        return;
      }
      
      try {
        const results = await portfolioApi.searchWorks(searchTerm);
        setFilteredWorks(results);
      } catch (err) {
        console.error('搜索失败:', err);
        // 降级到本地搜索
        const term = searchTerm.toLowerCase();
        const results = works.filter(work => 
          work.title.toLowerCase().includes(term) ||
          work.creator.toLowerCase().includes(term) ||
          work.description.toLowerCase().includes(term) ||
          (work.tags && work.tags.some(tag => tag.toLowerCase().includes(term)))
        );
        setFilteredWorks(results);
      }
    };

    performSearch();
  }, [searchTerm, works]);

  // 管理员登录
  const handleAdminLogin = async (username, password) => {
    try {
      const result = await portfolioApi.adminLogin(username, password);
      if (result.success) {
        setIsAdmin(true);
        setCurrentAdmin(result.admin);
        // 加载该管理员的课程
        await loadCourses(result.admin.id);
        // 加载该管理员的作品（通过课程关联）
        await loadAdminWorks(result.admin.id);
        return true;
      }
      return false;
    } catch (err) {
      console.error('管理员登录失败:', err);
      setError(err.message || '登录失败');
      return false;
    }
  };

  // 管理员登出
  const handleAdminLogout = () => {
    setIsAdmin(false);
    setCurrentAdmin(null);
    setAdminPassword('');
    setCourses([]);
  };

  // 添加作品
  const addWork = async (newWork) => {
    try {
      const addedWork = await portfolioApi.addWork(newWork);
      setWorks([...works, addedWork]);
      return addedWork;
    } catch (err) {
      console.error('添加作品失败:', err);
      setError(err.message || '添加作品失败，请重试');
      throw err;
    }
  };

  // 更新作品
  const updateWork = async (updatedWork) => {
    try {
      const updated = await portfolioApi.updateWork(updatedWork);
      setWorks(works.map(work => 
        work.id === updated.id ? updated : work
      ));
      return updated;
    } catch (err) {
      console.error('更新作品失败:', err);
      setError(err.message || '更新作品失败，请重试');
      throw err;
    }
  };

  // 删除作品
  const deleteWork = async (id) => {
    try {
      await portfolioApi.deleteWork(id);
      setWorks(works.filter(work => work.id !== id));
      return true;
    } catch (err) {
      console.error('删除作品失败:', err);
      setError(err.message || '删除作品失败，请重试');
      throw err;
    }
  };

  // 打开编辑模态框
  const openEditModal = (work) => {
    setCurrentWork(work);
    setIsModalOpen(true);
  };

  // 关闭模态框
  const closeModal = () => {
    setIsModalOpen(false);
    setCurrentWork(null);
  };

  // 课程管理方法
  const addCourse = async (courseData) => {
    try {
      const newCourse = await portfolioApi.addCourse({
        ...courseData,
        adminId: currentAdmin?.id
      });
      setCourses([...courses, newCourse]);
      return newCourse;
    } catch (err) {
      console.error('添加课程失败:', err);
      setError(err.message || '添加课程失败');
      throw err;
    }
  };

  const updateCourse = async (courseData) => {
    try {
      const updated = await portfolioApi.updateCourse(courseData);
      setCourses(courses.map(course => 
        course.id === updated.id ? updated : course
      ));
      return updated;
    } catch (err) {
      console.error('更新课程失败:', err);
      setError(err.message || '更新课程失败');
      throw err;
    }
  };

  const deleteCourse = async (id) => {
    try {
      await portfolioApi.deleteCourse(id);
      setCourses(courses.filter(course => course.id !== id));
      return true;
    } catch (err) {
      console.error('删除课程失败:', err);
      setError(err.message || '删除课程失败');
      throw err;
    }
  };

  const openCourseModal = (course = null) => {
    setCurrentCourse(course);
    setIsCourseModalOpen(true);
  };

  const closeCourseModal = () => {
    setIsCourseModalOpen(false);
    setCurrentCourse(null);
  };

  // 分页方法
  const changePage = useCallback((page) => {
    loadWorks(page, pagination.limit);
  }, [loadWorks, pagination.limit]);

  // 提供给子组件的数据和方法
  const value = {
    works: filteredWorks,
    allWorks: works,
    searchTerm,
    setSearchTerm,
    isAdmin,
    currentAdmin,
    adminPassword,
    setAdminPassword,
    handleAdminLogin,
    handleAdminLogout,
    addWork,
    updateWork,
    deleteWork,
    isModalOpen,
    currentWork,
    openEditModal,
    closeModal,
    loading,
    error,
    setError,
    loadWorks,
    // 课程相关
    courses,
    currentCourse,
    isCourseModalOpen,
    addCourse,
    updateCourse,
    deleteCourse,
    openCourseModal,
    closeCourseModal,
    loadCourses,
    // 分页相关
    pagination,
    changePage,
    // 管理员相关
    loadAdminWorks
  };

  return (
    <PortfolioContext.Provider value={value}>
      {children}
    </PortfolioContext.Provider>
  );
};

// 自定义Hook，方便组件使用上下文
export const usePortfolio = () => useContext(PortfolioContext);
